package com.hefan.live.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.cat.tiger.service.JedisService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.cat.tiger.util.CollectionUtils;
import com.cat.tiger.util.GlobalConstants;
import com.hefan.common.util.MapUtils;
import com.hefan.live.itf.LivingListService;
import com.hefan.live.itf.LivingRedisOptService;
import com.hefan.notify.bean.ListHotIndexVo;

/**
 * 直播列表处理
 * 
 * @author kevin_zhang
 *
 */
@Component("livingListService")
public class LivingListServiceImpl implements LivingListService {
	public Logger logger = LoggerFactory.getLogger(LivingListServiceImpl.class);

	@Resource
	JedisService jedisService;
	@Resource
	JdbcTemplate jdbcTemplate;
	@Resource
    LivingRedisOptService livingRedisOptService;

	/**
	 * 获取所有正在直播的直播间人数
	 * 
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	@Override
	public List getLivingRoomPeopleCount() {
		StringBuilder sql = new StringBuilder();
		sql.append(" SELECT COUNT(*) peopleCount, lr.chat_room_id chatRoomId from live_log_person llp, live_room lr  ");
		sql.append(" where llp.chat_room_id=lr.chat_room_id and lr.live_uuid=llp.live_uuid and lr.status=" + GlobalConstants.AUTHOR_LIVING);
		sql.append(" GROUP BY lr.chat_room_id ORDER BY peopleCount DESC ");
		List result = jdbcTemplate.queryForList(sql.toString());
		return CollectionUtils.isNotEmpty(result) ? result : new ArrayList<>();
	}

	/**
	 * 获取正在直播的直播间信息
	 * 
	 * @param rule（0：无用户类型要求
	 *            1：网红 2:明星/片场）
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	private List<ListHotIndexVo> getLivingList(int rule) {
		StringBuilder sql = new StringBuilder();
		sql.append(" SELECT user_id userId ");
		sql.append(" FROM live_room WHERE ");
		sql.append(" status=" + GlobalConstants.AUTHOR_LIVING);
		if (rule == 1)
			sql.append(" AND type IN (1) ");
		else if (rule == 2)
			sql.append(" AND type IN (2,3) ");
		sql.append(" ORDER BY start_time DESC ");
		List<ListHotIndexVo> result = jdbcTemplate.query(sql.toString(),
				new BeanPropertyRowMapper(ListHotIndexVo.class));
		return CollectionUtils.isNotEmpty(result) ? result : new ArrayList<ListHotIndexVo>();
	}

	/**
	 * 
	 * @param list
	 * @return
	 */
	private List<ListHotIndexVo> getLiveList(List<ListHotIndexVo> list) {
		List<ListHotIndexVo> resultList = new ArrayList<ListHotIndexVo>();
		for (int i = 0; i < list.size(); i++) {
			ListHotIndexVo item = list.get(i);
			try {
				String redisStr = jedisService.getStr(GlobalConstants.LIVING_USER_KEY + item.getUserId());
				logger.info("直播间信息：" + redisStr);
				if (StringUtils.isNotBlank(redisStr))
					item = JSON.parseObject(redisStr, ListHotIndexVo.class);
				//TODO
			} catch (Exception e) {
				e.printStackTrace();
			}
			if (null != item) {
				item.setUserId(item.getUserId());
				resultList.add(item);
			}
		}
		return resultList;
	}
	
	/**
	 * 获取热门页正在直播的直播列表
	 * 
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public List getHotLivingList() {
		/**
		 * 规则：明星=片场>网红，在线观看人数倒序
		 */
		List<ListHotIndexVo> resultList = new ArrayList();
		
		List<ListHotIndexVo> starList = getLivingList(2);//片场，明星
		List<ListHotIndexVo> starOnlineList = getLivingList(1);//网红
		List livingRoomPeopleCount = getLivingRoomPeopleCount();//所有直播间观看人数
		
		starList = getLiveList(starList);
		starOnlineList = getLiveList(starOnlineList);
		
		for (int i = 0; i < livingRoomPeopleCount.size(); i++) {
			Map peopleMap = (Map) livingRoomPeopleCount.get(i);
			int peopleCount = MapUtils.getIntValue(peopleMap, "peopleCount", 0);
			int chatRoomId = MapUtils.getIntValue(peopleMap, "chatRoomId", 0);
			for (ListHotIndexVo item : starList) {
				if (item.getChatRoomId() == chatRoomId) {
					item.setPeopleCount(peopleCount);
					resultList.add(item);
					starList.remove(item);
					break;
				}
			}
		}
		resultList.addAll(starList);
		
		for (int i = 0; i < livingRoomPeopleCount.size(); i++) {
			Map peopleMap = (Map) livingRoomPeopleCount.get(i);
			int peopleCount = MapUtils.getIntValue(peopleMap, "peopleCount", 0);
			int chatRoomId = MapUtils.getIntValue(peopleMap, "chatRoomId", 0);
			for (ListHotIndexVo item : starOnlineList) {
				if (item.getChatRoomId() == chatRoomId) {
					item.setPeopleCount(peopleCount);
					resultList.add(item);
					starOnlineList.remove(item);
					break;
				}
			}
		}
		resultList.addAll(starOnlineList);
		
		return resultList;
	}

	/**
	 * 获取最新正在直播的直播列表
	 * 
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public List getLatestLivingList() {
		/**
		 * 规则：时间倒序
		 */
		List<ListHotIndexVo> resultList = new ArrayList();

		List<ListHotIndexVo> latestList = getLivingList(0);
		List livingRoomPeopleCount = getLivingRoomPeopleCount();// 所有直播间观看人数

		latestList = getLiveList(latestList);

		for (int i = 0; i < livingRoomPeopleCount.size(); i++) {
			Map peopleMap = (Map) livingRoomPeopleCount.get(i);
			int peopleCount = MapUtils.getIntValue(peopleMap, "peopleCount", 0);
			int chatRoomId = MapUtils.getIntValue(peopleMap, "chatRoomId", 0);
			for (ListHotIndexVo item : latestList) {
				if (item.getChatRoomId() == chatRoomId) {
					item.setPeopleCount(peopleCount);
					resultList.add(item);
					latestList.remove(item);
					break;
				}
			}
		}
		resultList.addAll(latestList);

		return resultList;
	}
}
